package com.webside.spread.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.webside.base.basecontroller.BaseController;
import com.webside.dtgrid.model.Pager;
import com.webside.dtgrid.util.ExportUtils;
import com.webside.exception.AjaxException;
import com.webside.exception.ServiceException;
import com.webside.exception.SystemException;
import com.webside.series.model.Bdictionary;
import com.webside.spread.model.GenerateLinksEntity;
import com.webside.spread.model.SpreadSupporterEntity;
import com.webside.spread.service.GenerateLinksService;
import com.webside.spread.service.SpreadService;
import com.webside.util.Common;
import com.webside.util.HttpUtil;
import com.webside.util.PageUtil;

import jodd.util.URLDecoder;

@Controller
@Scope("prototype")
@RequestMapping("/spreadlink/")
public class GeneraterLinksController extends BaseController{
	@Autowired
	private GenerateLinksService generateLinksService;
	@Autowired
	private SpreadService spreadService;
	@RequestMapping("listUI.html")
	public String listUI(Model model, HttpServletRequest request) {
		try
		{
			PageUtil page = new PageUtil();
			if(request.getParameterMap().containsKey("page")){
				page.setPageNum(Integer.valueOf(request.getParameter("page")));
				page.setPageSize(Integer.valueOf(request.getParameter("rows")));
				page.setOrderByColumn(request.getParameter("sidx"));
				page.setOrderByType(request.getParameter("sord"));
			}
			model.addAttribute("page", page);
			List<String> spreadNameList = spreadService.selectSpreadName();
			model.addAttribute("spreadNameList", spreadNameList);
			return Common.BACKGROUND_PATH + "/spread/generatelink";
		}catch(Exception e)
		{
			throw new SystemException(e);
		}
	}
	
	/**
	 * ajax分页动态加载模式
	 * @param dtGridPager Pager对象
	 * @throws Exception
	 */
	@RequestMapping(value = "/list.html", method = RequestMethod.POST)
	@ResponseBody
	public Object list(Model model,Long seriesId, String gridPager,Bdictionary channel,GenerateLinksEntity generateLinksEntity, HttpServletResponse response) throws Exception{
		
		Map<String, Object> parameters = null;
		// 映射Pager对象
		Pager pager = JSON.parseObject(gridPager, Pager.class);
		// 判断是否包含自定义参数
		parameters = pager.getParameters();
		if (parameters.size() < 0) {
			parameters.put("name", null);
		}
		//3、判断是否是导出操作
		if(pager.getIsExport())
		{
			if(pager.getExportAllData())
			{
				//3.1、导出全部数据
				List<GenerateLinksEntity> list = generateLinksService.queryAllLinks(parameters);
				ExportUtils.exportAll(response, pager, list);
				return null;
			}else
			{
				//3.2、导出当前页数据
				ExportUtils.export(response, pager);
				return null;
			}
		}else
		{
			
			// 设置分页，page里面包含了分页信息
			Page<Object> page = PageHelper.startPage(pager.getNowPage(),pager.getPageSize(), "");
			List<GenerateLinksEntity> list = generateLinksService.queryAllLinks(parameters);
			 
			parameters.clear();
			parameters.put("isSuccess", Boolean.TRUE);
			parameters.put("nowPage", pager.getNowPage());
			parameters.put("pageSize", pager.getPageSize());
			parameters.put("pageCount", page.getPages());
			parameters.put("recordCount", page.getTotal());
			parameters.put("startRecord", page.getStartRow());
			parameters.put("exhibitDatas", list);
			return parameters;
		}
		
	}
	//添加显示
		@RequestMapping("addUI.html")
		public String addUI(Model model, HttpServletRequest request) {
			return Common.BACKGROUND_PATH + "/spread/form";
		}
	
	@RequestMapping("update")
	public String update(Model model,GenerateLinksEntity link, HttpServletRequest request) {
		generateLinksService.updateLinks(link);
		
		return "spread";
	}
	
	
	//修改显示
		@RequestMapping("editUI.html")
		public String editUI(Model model, HttpServletRequest request, Long id) {
			
			try
			{
				Map<String,Object> param = new HashMap<>();
				param.put("id", id);
				List<GenerateLinksEntity> spread=generateLinksService.queryListByPage(param);
				/*PageUtil page = new PageUtil();
				page.setPageNum(Integer.valueOf(request.getParameter("page")));
				page.setPageSize(Integer.valueOf(request.getParameter("rows")));
				page.setOrderByColumn(request.getParameter("sidx"));
				page.setOrderByType(request.getParameter("sord"));
			
				model.addAttribute("page", page);*/
				model.addAttribute("spread", spread.get(0));

				return Common.BACKGROUND_PATH + "/spread/form";
			}catch(Exception e)
			{
				throw new SystemException(e);
			}
		}
		//修改
		@RequestMapping("edit.html")
		@ResponseBody
		public Object update(GenerateLinksEntity link)
		{
			Map<String, Object> map = new HashMap<String, Object>();
			
			try
			 {  	 
					
					int result = generateLinksService.updateLinks(link);
					System.out.println(result);
				if(result >0)
				{
					map.put("success", Boolean.TRUE);
					map.put("data", null);
					map.put("message", "编辑成功");
					
				}else
				{
					map.put("success", Boolean.FALSE);
					map.put("data", null);
					map.put("message", "编辑失败");
				}
			}catch(Exception e)
			{
				throw new AjaxException(e);
			}
			return map;
		}
		//删除
		@RequestMapping("deleteBatch.html")
		@ResponseBody
		public Object delete(String ids) {
			Map<String, Object> result = new HashMap<String, Object>();
			try
			{
				String[] Ids = ids.split(",");
				List<String> list = new ArrayList<String>();
				for (String string : Ids) {
					list.add(String.valueOf(string));
				}
				int cnt = generateLinksService.deleteLinks(list);
				System.out.println(cnt);
				if(cnt !=0)
				{
					result.put("success", true);
					result.put("data", null);
					result.put("message", "删除成功");
				}else
				{
					result.put("success", false);
					result.put("data", null);
					result.put("message", "删除失败");
				}
			}catch(Exception e)
			{
				throw new AjaxException(e);
			}
			return result;
		}
		/**
		 * 查询推广选单
		 * @param model
		 * @param request
		 * @return
		 */
		@RequestMapping("generatelink.html")
		public String makeShortURI(Model model, HttpServletRequest request) {
			try
			{
				PageUtil page = new PageUtil();
				if(request.getParameterMap().containsKey("page")){
					page.setPageNum(Integer.valueOf(request.getParameter("page")));
					page.setPageSize(Integer.valueOf(request.getParameter("rows")));
					page.setOrderByColumn(request.getParameter("sidx"));
					page.setOrderByType(request.getParameter("sord"));
				}
				model.addAttribute("page", page);
				List<Map<String,Object>> spreadNameList = spreadService.selectSpreadNameAll();
				model.addAttribute("spreadNameList", spreadNameList);
				return Common.BACKGROUND_PATH + "/spread/makeshortURI";
			}catch(Exception e)
			{
				throw new SystemException(e);
			}
		}
		/**
		 * 添加短链接
		 * @param model
		 * @param spreadName
		 * @param oriLink
		 * @param request
		 * @return
		 * @throws ParseException 
		 * @throws UnsupportedEncodingException 
		 */
		@RequestMapping(value = "add.html", method = RequestMethod.POST)
		@ResponseBody
		public Object add(Model model, @RequestParam("spreadName[]")String[] spreadName,@RequestParam("oriLink") String oriLink, HttpServletRequest request) throws ParseException, UnsupportedEncodingException {
			System.out.println(spreadName);
			System.out.println(oriLink);
			Map<String, Object> map = new HashMap<String, Object>();
			try
			{	String oriLink1="";
				String oriLink2="";
				List<Map<String,Object>> spreadNameList = spreadService.selectSpreadNameAll();
				List<String> shortlink = new ArrayList<String>();
				for (int i = 0; i < spreadName.length; i++) {
					String name="";
					for (int j = 0; j < spreadNameList.size(); j++) {
						String code=(String) spreadNameList.get(j).get("code");
						if( code.equals(spreadName[i])){
							name =(String) spreadNameList.get(j).get("name");
						}
					}
					String tag="";
					if (oriLink.contains("?")) {
						tag = "&spread_source="+spreadName[i];
					}else{
						tag = "?spread_source="+spreadName[i];
					}
					oriLink2 =oriLink+tag;
					oriLink2 = URLEncoder.encode(oriLink2, "utf-8");
					System.out.println("加tag："+oriLink2);
					oriLink1 ="http://api.t.sina.com.cn/short_url/shorten.json?source=3153789393&url_long="+ oriLink2;
					//生成短连接
					Object  returnJson= HttpUtil.executeHttpGet(oriLink1);
					String sl = returnJson.toString();
					JSONArray jsonArray  = JSONArray.parseArray(sl);
					String slink="";
					String slink1="";
					if(jsonArray.size()>0){
						JSONObject jsonO = jsonArray.getJSONObject(0);
						slink1=(String) jsonO.get("url_short")+"?"+name;
						slink =name +"&nbsp;&nbsp;:&nbsp;&nbsp;"+ (String) jsonO.get("url_short")+"?"+name;
						
					}
					shortlink.add(slink);
					//存储短链接
					GenerateLinksEntity shLink = new GenerateLinksEntity();
					Date day=new Date(); 
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
					String t = df.format(day);
					Date day1=df.parse(t);
					shLink.setCreateTime(day1);
					shLink.setOriLink(oriLink);
					
					shLink.setSsCode(spreadName[i]);
					shLink.setSsName(name);
					shLink.setShortLink(slink1);
					generateLinksService.addLinks(shLink);
				}
				
				/*int count=generateLinksService.addLinks( , oriLink);*/
				int count=1;
				 
				if(count >0 )
				{
					map.put("success", Boolean.TRUE);
					map.put("data", null);
					map.put("linkList", shortlink);
					map.put("message", "添加成功");
				}else
				{
					map.put("success", Boolean.FALSE);
					map.put("data", null);
					map.put("message", "添加失败");
				}
			}catch(ServiceException e)
			{
				throw new AjaxException(e);
			}
			return map;
		}
}
